package com.netsdk.demo.frame.Gate;

import com.netsdk.common.Res;
import com.netsdk.demo.module.GateModule;
import com.netsdk.demo.module.LoginModule;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.NetSDKLib.LLong;
import com.netsdk.lib.ToolKits;
import com.sun.jna.Callback;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

public class Gate {


    //设备信息
    private static NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
    //通道
    public static Vector<String> chnList = new Vector<String>();

    // 设备断线通知回调
    private static DisConnect disConnect = new DisConnect();

    private static class DisConnect implements NetSDKLib.fDisConnect {
        @Override
        public void invoke(LLong lLoginID, String pchDVRIP, int nDVRPort, Pointer dwUser) {
        }
    }

    // 订阅句柄
    public static LLong m_hAttachHandle = new LLong(0);

    private static AnalyzerDataCB analyzerCallback = new AnalyzerDataCB();

    private static class AnalyzerDataCB implements NetSDKLib.fAnalyzerDataCallBack, Callback {
        private BufferedImage gateBufferedImage = null;


        public int invoke(LLong lAnalyzerHandle, int dwAlarmType,
                          Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                          Pointer dwUser, int nSequence, Pointer reserved) throws UnsupportedEncodingException {
            if (lAnalyzerHandle.longValue() == 0 || pAlarmInfo == null) {
                return -1;
            }

            //netsdk.CLIENT_SetDVRMessCallBack(null,dwUser);


            File path = new File("./GateSnapPicture/");
            if (!path.exists()) {
                path.mkdir();
            }

            ///< 门禁事件
            if (dwAlarmType == NetSDKLib.EVENT_IVS_ACCESS_CTL) {
                NetSDKLib.DEV_EVENT_ACCESS_CTL_INFO msg = new NetSDKLib.DEV_EVENT_ACCESS_CTL_INFO();
                ToolKits.GetPointerData(pAlarmInfo, msg);
                // 时间
                if (msg.UTC != null || msg.UTC.toString().isEmpty()) {
                    msg.UTC.setTime(msg.UTC.dwYear, msg.UTC.dwMonth, msg.UTC.dwDay, msg.UTC.dwHour + 8, msg.UTC.dwMinute, msg.UTC.dwSecond);
                    System.out.println("时间-----" + msg.UTC.toString());
                }
                String status = null;
                // 开门状态
                if (msg.bStatus == 1) {
                    status = Res.string().getSucceed();
                    System.out.println("开门状态----" + Res.string().getSucceed());
                } else {
                    status = Res.string().getFailed();
                    System.out.println("开门状态----" + Res.string().getFailed());
                }

                // 开门方式
                String kmfs = Res.string().getOpenMethods(msg.emOpenMethod);
                System.out.println("开门方式---" + Res.string().getOpenMethods(msg.emOpenMethod));

                // 卡名
                String km = null;
                try {
                    km = new String(msg.szCardName, "GBK").trim();
                    System.out.println("卡名----" + km);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String kh = new String(msg.szCardNo).trim();
                // 卡号
                System.out.println("卡号----" + kh);

                // 用户ID
                System.out.println("用户ID----" + new String(msg.szUserID).trim());

                // 口罩状态
                System.out.println("口罩状态----" + Res.string().getMaskStatus(msg.emMask));
                //温度
                String temper = null;
                if (msg.stuManTemperatureInfo.emTemperatureUnit == 0) {
                    temper = msg.stuManTemperatureInfo.fCurrentTemperature + "℃";
                    System.out.println("温度----" + String.valueOf(msg.stuManTemperatureInfo.fCurrentTemperature + "℃"));
                } else if (msg.stuManTemperatureInfo.emTemperatureUnit == 1) {
                    System.out.println("温度----" + String.valueOf(msg.stuManTemperatureInfo.fCurrentTemperature + "℉"));
                    temper = msg.stuManTemperatureInfo.fCurrentTemperature + "℉";
                } else if (msg.stuManTemperatureInfo.emTemperatureUnit == 2) {
                    System.out.println("温度----" + String.valueOf(msg.stuManTemperatureInfo.fCurrentTemperature + "K"));
                    temper = msg.stuManTemperatureInfo.fCurrentTemperature + "K";
                }
                if (km!= null && kh != null) {
                    RestTemplate restTemplate = new RestTemplate();
                            //103.219.33.112
                    String url = "http://103.219.33.112:10010/insertdhsdk?kh=" + kh + "&kmfs=" + kmfs + "&name=" + km +
                            "&status=" + status + "&temper=" + temper + "&schoolId="+4;
                    String forObject = restTemplate.getForObject(url, String.class);
                    String[] split = forObject.split("-");
                    //健康码-----身份证
                    System.out.println("健康码---------"+split[1]);
                    System.out.println("身份证---------"+split[0]);
                    Gate.openDoorByFace(split[1],split[0]);
                }
            }
            // 保存图片，获取图片缓存
            String snapPicPath = path + "\\" + System.currentTimeMillis() + "GateSnapPicture.jpg";  // 保存图片地址
            byte[] buffer = pBuffer.getByteArray(0, dwBufSize);
            ByteArrayInputStream byteArrInputGlobal = new ByteArrayInputStream(buffer);

            try {
                gateBufferedImage = ImageIO.read(byteArrInputGlobal);
                if (gateBufferedImage != null) {
                    ImageIO.write(gateBufferedImage, "jpg", new File(snapPicPath));
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }

            return 0;
        }
    }

/*    private static FMessCallBack fMessCallBack = new FMessCallBack();

    private static class FMessCallBack implements NetSDKLib.fMessCallBack,Callback{
        @Override
        public boolean invoke(int lCommand, LLong lLoginID, Pointer pStuEvent, int dwBufLen, String strDeviceIP, NativeLong nDevicePort, Pointer dwUser) {
            System.out.println("111");
            return false;
        }
    }*/

    // 网络连接恢复
    private static HaveReConnect haveReConnect = new HaveReConnect();

    private static class HaveReConnect implements NetSDKLib.fHaveReConnect {
        public void invoke(LLong m_hLoginHandle, String pchDVRIP, int nDVRPort, Pointer dwUser) {
            System.out.printf("ReConnect Device[%s] Port[%d]\n", pchDVRIP, nDVRPort);

        }
    }



    private static long loginHandler;
    //private static int userId;

    public static void start() {
        //初始化
        System.out.println("开始初始化");
        if (LoginModule.init(disConnect, haveReConnect)) {
            System.out.println("初始化成功");
            //登录
            System.out.println("开始登录");
            //183.135.184.32
            loginHandler = LoginModule.login("192.168.1.106", 37777, "admin"
                    , "admin123");
            if (loginHandler == 0 ? false : true) {
                System.out.println("登录成功");
                //获取通道
                for (int i = 1; i < LoginModule.m_stDeviceInfo.byChanNum + 1; i++) {
                    chnList.add(Res.string().getChannel() + " " + String.valueOf(i));
                }
                System.out.println(chnList); //打印通道
                //设置通道
                if (chnList.size() > 0) {
                    m_hAttachHandle = GateModule.realLoadPic(0, analyzerCallback);
                } else {
                    System.out.println("查询不到通道");
                }
            } else {
                System.out.println("登录失败");
            }
        } else {
            System.out.println("初始化失败");
        }

    }

    public static void openDoorByFace(String healthCode,String idno) {
        //入参
        NetSDKLib.NET_IN_FACE_OPEN_DOOR pInParam = new NetSDKLib.NET_IN_FACE_OPEN_DOOR();
        pInParam.nChannel = 0;
        //比对结果需要填正数
        pInParam.emCompareResult = 1;
        //byte[] UserID = "4".getBytes();
        //byte[] UserID = "3".getBytes();
        NetSDKLib.NET_HEALTH_CODE_INFO health_code_info = new NetSDKLib.NET_HEALTH_CODE_INFO();
        byte[] citizenID =idno.getBytes();
        /*health_code_info.szCitizenID = sfz;
        pInParam.stuMatchInfo.szUserID = UserID;*/
        System.arraycopy(citizenID, 0, health_code_info.szCitizenID, 0, citizenID.length);
       // NetSDKLib.NET_OPENDOOR_MATCHINFO stuMatchInfo = new NetSDKLib.NET_OPENDOOR_MATCHINFO();
/*
              stuMatchInfo.szUserID=UserID;
        stuMatchInfo.szUserName="李安".getBytes();
        stuMatchInfo.emUserType=1;
        stuMatchInfo.szName="kaimen".getBytes();
        pInParam.stuMatchInfo=stuMatchInfo;*/
       /* NetSDKLib.NET_OPENDOOR_IMAGEINFO stuImageInfo = new NetSDKLib.NET_OPENDOOR_IMAGEINFO();
        pInParam.stuImageInfo=stuImageInfo;*/
        //360502199710276013
        //byte[] sfz = "360502199710276013".getBytes();
        if(healthCode.equals("green")){
            health_code_info.emHealthCodeStatus = NetSDKLib.EM_HEALTH_CODE_STATUS.EM_HEALTH_CODE_STATUS_GREEN.ordinal();
        }
        if(healthCode.equals("red")){
            health_code_info.emHealthCodeStatus = NetSDKLib.EM_HEALTH_CODE_STATUS.EM_HEALTH_CODE_STATUS_RED.ordinal();
        }
        if(healthCode.equals("yellow")){
            health_code_info.emHealthCodeStatus = NetSDKLib.EM_HEALTH_CODE_STATUS.EM_HEALTH_CODE_STATUS_YELLOW.ordinal();
        }
        if(!healthCode.equals("yellow") && !healthCode.equals("green") && !healthCode.equals("red")){
            health_code_info.emHealthCodeStatus= NetSDKLib.EM_HEALTH_CODE_STATUS.EM_HEALTH_CODE_STATUS_INVALID.ordinal();
       }
        pInParam.stuMatchInfo.pstuHealthCodeInfo = new Memory(health_code_info.size());
        ToolKits.SetStructDataToPointer(health_code_info, pInParam.stuMatchInfo.pstuHealthCodeInfo, 0);
        //出参
        NetSDKLib.NET_OUT_FACE_OPEN_DOOR pOutParam = new NetSDKLib.NET_OUT_FACE_OPEN_DOOR();
        boolean bRet = netsdk.CLIENT_FaceOpenDoor(new NetSDKLib.LLong(loginHandler), pInParam, pOutParam, 3000);
        if (!bRet) {
            System.out.println("找不到健康码！");
            return;
        } else {
            System.out.println("同步健康码成功");
        }
    }
   /* public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                //初始化
                System.out.println("开始初始化");
                if (LoginModule.init(disConnect, haveReConnect)) {
                    System.out.println("初始化成功");
                    //登录
                    System.out.println("开始登录");
                    if (LoginModule.login("183.135.184.32", 37777, "admin"
                            , "admin123")) {
                        System.out.println("登录成功");
                        //获取通道
                        for (int i = 1; i < LoginModule.m_stDeviceInfo.byChanNum + 1; i++) {
                            chnList.add(Res.string().getChannel() + " " + String.valueOf(i));
                        }
                        System.out.println(chnList); //打印通道
                        //设置通道
                        if (chnList.size() > 0) {
                            m_hAttachHandle = GateModule.realLoadPic(1, analyzerCallback);
                        } else {
                            System.out.println("查询不到通道");
                        }
                    } else {
                        System.out.println("登录失败");
                    }
                } else {
                    System.out.println("初始化失败");
                }

            }
        });

    }*/
}










